#include "xplreader.h"
#include "xmlformat.h"
#include <QDir>
#include <QDebug>
#include "logger.h"

template <class T> class VPtr
{
public:
    static T* asPtr(QVariant v)
    {
        return  (T *) v.value<void *>();
    }

    static QVariant asQVariant(T* ptr)
    {
        return qVariantFromValue((void *) ptr);
    }
};

XplReader::XplReader()
{
    QDir( QDir::homePath()).mkdir(".flr");
}
bool XplReader::Open(QString FileName)
{
   QDir dir = QDir( QDir::homePath());
   dir.cd(".flr");

    m_playlist = new QSettings(dir.absoluteFilePath(FileName), XmlFormat::getFormat());
    if (m_playlist == NULL)
        return false;

    if (m_playlist->value("Version").toInt() != XPL_VERSION)
    {
        qLog.error("radio.xpl hat die falsche Version!");
        return false;
    }
    qLog.ok("radio.xpl erfolgreich geladen");
    return true;
}

void XplReader::WriteInQComboBox(QComboBox *lsview)
{
    if(!m_playlist || !lsview) return;
    lsview->clear();
    int m_entrys = m_playlist->value("Items", 0).toInt();


    for(int i=0; i < m_entrys; i++)
    {
      m_playlist->beginGroup(QString("Item") + QString::number(i));
      xplEntry *entry = new xplEntry(m_playlist->value(QString("Name"), "-NOT_A_TAG").toString(),
                                    m_playlist->value(QString("URL"), "-NOT_A_FILE").toString());
      m_playlist->endGroup();


      WriteInQComboBox(lsview, entry);
    }

}
void XplReader::WriteInQComboBox(QComboBox *lsview, xplEntry *entry)
{
    if(entry->getURL() != "-NOT_A_FILE")
    {
      lsview->addItem(entry->getName() != "-NOT_A_TAG" ? entry->getName() : entry->getURL(), VPtr<xplEntry>::asQVariant( entry));
      qLog.ok("Entry: " + entry->getName() + " ( " + entry->getURL() + " ) geladen");
    }
}

void XplReader::SaveInFileFromQComboBox(QComboBox* lsview)
{
    if(!m_playlist) return;

    m_playlist->setValue("Items", lsview->count());
    m_playlist->setValue("Version", XPL_VERSION);

    qLog.info("Speichere neue radio.xpl ( Version: " + QString(XPL_VERSION_STRING) + " Items: " + m_playlist->value("Version").toString() + " )");
    for(int i=0; i < lsview->count(); i++)
    {
        xplEntry *entry = VPtr<xplEntry>::asPtr(lsview->itemData(i));

        m_playlist->beginGroup(QString("Item") + QString::number(i));
        m_playlist->setValue(QString("Name"), entry->getName());
        m_playlist->setValue(QString("URL"), entry->getURL());
        m_playlist->endGroup();
    }
}
QString XplReader::getURL(QComboBox* lsview, int i)
{
    return VPtr<xplEntry>::asPtr(lsview->itemData(i))->getURL();
}

bool XplReader::Close()
{
    if(m_playlist)
    {
        delete m_playlist;
        return true;
    }
    return false;
}
